package com.yuma.tingshu.user.api;

import com.yuma.tingshu.common.annotation.YuMaLogin;
import com.yuma.tingshu.common.result.Result;
import com.yuma.tingshu.common.util.AuthContextHolder;
import com.yuma.tingshu.model.user.UserInfo;
import com.yuma.tingshu.user.login.LoginAccount;
import com.yuma.tingshu.user.login.LoginClient;
import com.yuma.tingshu.user.login.LoginType;
import com.yuma.tingshu.user.service.UserInfoService;
import com.yuma.tingshu.vo.user.UserInfoVo;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@Tag(name = "微信授权登录接口")
@RestController
@Slf4j
@RequestMapping("/api/user/wxLogin")
public class WxLoginApiController {

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private LoginClient loginClient;

//    @Autowired
//    private UserAccountService userAccountService;

    /*@GetMapping("wxLogin/{code}")
    public Result<Map<String,Object>> wxLogin(@PathVariable String code) throws Exception {
        Map<String,Object> map = this.userInfoService.wxLogin(code);
        return Result.ok(map);
    }*/

    // 策略模式
    @GetMapping("wxLogin/{code}")
    public Result<Map<String, Object>> wxLogin(@PathVariable String code) throws Exception {
        LoginAccount account = new LoginAccount();
        account.setCode(code);
        return Result.ok(loginClient.login(LoginType.WX_LOGIN.type, account));
    }

    /**
     * 根据用户id查询用户
     *
     * @return
     */
    @YuMaLogin
    @GetMapping("getUserInfo")
    public Result<UserInfoVo> getUserInfo() {
        Long userId = AuthContextHolder.getUserId();
        UserInfo userInfo = this.userInfoService.getById(userId);
        UserInfoVo userInfoVo = new UserInfoVo();
        BeanUtils.copyProperties(userInfo, userInfoVo);
        return Result.ok(userInfoVo);
    }

    /**
     * 更新用户的登录信息
     *
     * @param userInfoVo
     * @return
     */
    @YuMaLogin
    @PostMapping("updateUser")
    @Operation(summary = "更新用户的登录信息")
    public Result updateUser(@RequestBody UserInfoVo userInfoVo) {
        // 获取登录用户id
        Long userId = AuthContextHolder.getUserId();
        UserInfo userInfo = new UserInfo();
        // 设置更新参数
        userInfo.setId(userId);
        userInfo.setAvatarUrl(userInfoVo.getAvatarUrl());
        userInfo.setNickname(userInfoVo.getNickname());
        // 根据id更新用户
        this.userInfoService.updateById(userInfo);
        return Result.ok();
    }

}
